package com.iretailer.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间处理的工具类
 *
 * @author xjwtt
 * @date 2018/8/24
 */
public class TimeUtil {


    /**
     * 获取时区
     */
    public static final ZoneId zone = ZoneId.systemDefault();


    /**
     * LocalDate 转为 String
     * @param date
     * @return
     */
    public static String localDate2Str(LocalDate date){
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String localDate2Str(LocalDate date,String formatter){
        return date.format(DateTimeFormatter.ofPattern(formatter));
    }

    /**
     * 字符串日期转为 LocalDate
     *
     * @param strDate
     * @return
     */
    public static LocalDate str2Date(String strDate) {
        return LocalDate.parse(strDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 字符串日期，按照定义的格式转
     *
     * @param strDate
     * @param formatter
     * @return
     */
    public static LocalDate str2Date(String strDate, String formatter) {
        return LocalDate.parse(strDate, DateTimeFormatter.ofPattern(formatter));
    }

    /**
     * 字符串 日期时间，转为 LocalDateTime
     *
     * @param strDateTime
     * @return
     */
    public static LocalDateTime str2DateTime(String strDateTime) {
        return LocalDateTime.parse(strDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 字符串 日期时间，按照定义的格式转为LocalDateTime
     *
     * @param strDateTime
     * @param formatter
     * @return
     */
    public static LocalDateTime str2DateTime(String strDateTime, String formatter) {
        return LocalDateTime.parse(strDateTime, DateTimeFormatter.ofPattern(formatter));
    }

    /**
     * 得到 毫秒的 Long
     *
     * @param localDateTime
     * @return
     */
    public static Long getTime(LocalDateTime localDateTime) {
        return localDateTime.atZone(zone).toInstant().toEpochMilli();
    }

    /**
     * 计算两个日期之间相差几天
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long daysBetween(LocalDate startDate, LocalDate endDate) {
//        Period period = Period.between(startDate, endDate);
//        Long d1 = startDate.get
//        return period.getDays();
        long d1 = startDate.toEpochDay();
        long d2 = endDate.toEpochDay();

        return d2 - d1;
    }

    /**
     * 计算两个日期之间相差多少天
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long daysBetween(String startDate, String endDate) {
        return daysBetween(str2Date(startDate), str2Date(endDate));
    }

}
